<script setup lang="ts">
  import { ref, computed, watch } from 'vue';
  import dayjs from 'dayjs';
  import ListSelect from '@/components/list-select/index.vue';
  import useDetailDrawerHandler from '@/hooks/arco/useDetailDrawerHandler';
  import ModalAddProject from './modal-add-project.vue';

  const props = defineProps<{
    startDate: string;
    endDate: string;
  }>();

  const emits = defineEmits(['next']);

  const currentMonth = ref();

  const monthData = ref<Map<string, any[]>>(new Map());

  const dateList = computed(() => {
    // 检查日期是否有效
    if (!props.startDate || !props.endDate) {
      return [];
    }

    const start = dayjs(props.startDate);
    const end = dayjs(props.endDate);

    // 如果开始日期晚于结束日期，返回空数组
    if (start.isAfter(end)) {
      return [];
    }

    const dates = [];

    // 生成月份列表
    let current = start;
    while (current.isBefore(end) || current.isSame(end, 'month')) {
      dates.push({
        name: current.format('YYYY-MM'),
        value: current.format('YYYY-MM'),
      });
      current = current.add(1, 'month');
    }

    return dates;
  });

  watch(
    dateList,
    (val) => {
      monthData.value.clear();
      val.forEach((month) => {
        monthData.value.set(month.value, []);
      });
    },
    { deep: true, immediate: true }
  );

  const renderProjectData = computed(() => {
    return monthData.value.get(currentMonth.value);
  });

  const onMonthItemClick = (month: any) => {
    currentMonth.value = month.name;
  };

  const projectColumns = [
    {
      title: '所属分类',
      dataIndex: 'serviceCatName',
    },
    {
      title: '项目名称',
      dataIndex: 'name',
    },
    {
      title: '收费标准',
      dataIndex: 'priceModelName',
    },
    {
      title: '项目单价（元）',
      dataIndex: 'price',
    },
    {
      title: '数量',
      dataIndex: 'countPerMonth',
      slotName: 'countPerMonth',
    },
    {
      title: '操作',
      dataIndex: 'action',
      slotName: 'action',
    },
  ];

  const projectData = ref<any[]>([]);

  const handler = useDetailDrawerHandler();

  const onCreate = (data: any, extra: any) => {
    data.month.forEach((month: any) => {
      monthData.value.get(month)?.push({
        serviceCatName: extra.serviceCatName,
        name: extra.name,
        priceModelName: extra.priceModelName,
        price: extra.price,
        countPerMonth: Number(data.count),
      });
    });
  };

  const deleteProject = (index: number) => {
    projectData.value.splice(index, 1);
  };

  watch(monthData, (val) => {
    console.log('monthData', val);

    let isEmpty = true;

    Array.from(val.values()).forEach((element) => {
      if (element.length > 0) {
        isEmpty = false;
      }
    });

    if (isEmpty) {
      emits('next', {
        key: 'project',
        value: val,
      });
    } else {
      emits('next', false);
    }
  });
</script>

<template>
  <div class="flex h-full p-[20px] gap-[10px]">
    <div class="w-[200px] flex flex-col gap-[10px]">
      <a-button type="primary" @click="handler.showAdd()">添加项目</a-button>
      <ListSelect :data="dateList" @change="onMonthItemClick" />
    </div>
    <a-divider direction="vertical" class="h-full"></a-divider>
    <div class="flex-1">
      <a-table
        :columns="projectColumns"
        :data="renderProjectData"
        :pagination="false"
      >
        <template #countPerMonth="{ record }">
          <a-input-number
            v-model="record.countPerMonth"
            mode="button"
            size="small"
            class="w-[150px]"
          />
        </template>
        <template #action="{ index }">
          <a-button
            type="text"
            status="danger"
            size="small"
            @click="deleteProject(index)"
          >
            删除
          </a-button>
        </template>
      </a-table>

      <ModalAddProject
        :month-list="dateList"
        v-bind="handler.bindProps"
        @success="onCreate"
      />
    </div>
  </div>
</template>

<style lang="less" scoped></style>
